package com.kuaiyin.executor;

import com.fasterxml.jackson.databind.JsonNode;
import com.kuaiyin.entity.Request;
import com.kuaiyin.entity.TestCase;
import com.kuaiyin.mapper.RequestMapper;
import com.kuaiyin.mapper.TestCaseMapper;
import com.kuaiyin.mapper.TestPlanCaseMapper;
import com.kuaiyin.utils.JsonFieldFinder;
import com.kuaiyin.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;

@Slf4j
public class TestPlanExecutor extends AbstractRequestExecutor {

    private final TestCaseMapper testCaseMapper;
    private final RequestMapper requestMapper;
    private final TestPlanCaseMapper testPlanCaseMapper;
    private final Long testCaseId;
    private final Long planId;

    private static final String REDIS_KEY_PATTERN = "testPlan_id_%d_testCase_id_%d";   //  将请求和响应数据存入 Redis

    public TestPlanExecutor(TestCaseMapper testCaseMapper, RequestMapper requestMapper, TestPlanCaseMapper testPlanCaseMapper, RedisUtils redisUtils, Long testCaseId, Long planId) {
        super(redisUtils);
        this.testCaseMapper = testCaseMapper;
        this.requestMapper = requestMapper;
        this.testPlanCaseMapper = testPlanCaseMapper;
        this.testCaseId = testCaseId;
        this.planId = planId;
    }

    @Override
    protected Request getRequest(Long id) {
        TestCase testCase = testCaseMapper.selectById(id);
        return requestMapper.selectById(testCase.getRequestId());
    }

    @Override
    protected String getEnvironmentType(Long id) {
        return testCaseMapper.selectById(id).getEnvironmentType();
    }

    @Override
    protected Map<String, Object> getAssertions(Long id) {
        return testCaseMapper.selectById(id).getAssertions();
    }

    @Override
    protected void updateExecutionStatus(Long id, String status) {
        TestCase testCase = testCaseMapper.selectById(id);
        testCase.setExecStatus(status);
        testCaseMapper.updateById(testCase);
    }

    @Override
    protected void extractAndSaveResponse(Long id, String environmentType, JsonNode response) {
        JsonFieldFinder finder = null;
        try {
            finder = new JsonFieldFinder(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 获取要提取的字段配置（可能是 JSON 字符串）
        Map<String, String> responseExtract = testPlanCaseMapper.getResponseExtract(planId, id);

        if (responseExtract == null || responseExtract.isEmpty()) {
            return; // 没有字段需要提取
        }
        String fieldConfigJson = responseExtract.values().iterator().next();  // 从 Map 中获取 JSON 字符串
        Map<String, Object> extractedValues = finder.extractAndAssignMultipleFields(fieldConfigJson); //  提取字段
        String redisKey = String.format("testPlan_id_%d_responseExtract_%s", planId, environmentType);// 将响应数据提取字段存入 Redis
        extractedValues.forEach((targetKey, value) -> {  // 将提取的字段保存到 Redis 中
            redisUtils.saveToHash(
                    redisKey,
                    86400L,
                    targetKey, value
            );
        });
    }

    @Override
    protected void saveToRedis(Long id, String url, Map<String, Object> body, Map<String, Object> headers, JsonNode response, Map<String, Object> assertions, String method) {
        String redisKey = String.format(REDIS_KEY_PATTERN, planId, id);
        redisUtils.saveToHash(
                redisKey,
                86400L,
                "requestUrl", url,
                "requestBody", body,
                "response", response,
                "requestHeader", headers,
                "assertions", assertions,
                "method", method
        );
    }
}
